package org.offsync.rich

import java.nio.channels.ServerSocketChannel
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.channels.Selector
import java.nio.channels.SelectionKey
import org.offsync.async.AcceptSelector

case class RichServerSocketChannel(val channel: ServerSocketChannel) {
  def onReady(
      acceptSelector: AcceptSelector)(
          f: () => Unit) = {
    acceptSelector.invoke { () =>
      channel.register(acceptSelector.selector, acceptSelector.op, f)
    }
  }
  
  def asyncConnect(
      selector: Selector,
      hostAddress: InetAddress,
      port: Int): Unit = {
    channel.configureBlocking(false);

    // Bind the server socket to the specified address and port
    channel.socket().bind(new InetSocketAddress(hostAddress, port));

    // Register the server socket channel, indicating an interest in 
    // accepting new connections
    channel.register(selector, SelectionKey.OP_ACCEPT);
  }
}
